var form = document.querySelector('form');
var username = document.querySelector('[name="username"]');
var password = document.querySelector('[name="password"]');
var repass = document.querySelector('[name="repass"]');
var nickname = document.querySelector('[name="nickname"]');
form.addEventListener('submit', submit)
function submit() {
    // 要加表单校验

    // 阻止默认行为
    window.event.returnValue = false
    // 发送请求
    var xhr = new XMLHttpRequest()
    xhr.open('post', 'http://localhost:8888/users/register')
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    var params = `username=${username.value}&password=${password.value}&rpassword=${repass.value}&nickname=${nickname.value}`
    xhr.send(params)
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            if(xhr.status>=200 && xhr.status<300) {
                var res = xhr.responseText
                res = JSON.parse(res)
                // console.log(res);
                var {message, code} = res
                if(code === 1) {
                    alert(message)
                    // 跳转到登录页面
                    location.href = 'login.html'
                } else {
                    alert(message)
                }
            }
        }
    }
}